<?php
/** @noinspection PhpUnused */

namespace app\shop\model\user;

use app\shop\model\BaseModel;
use think\facade\Db;

class UserModel extends BaseModel
{
    protected $name = 'shop_user';

    public function searchPhoneAttr($query, $value): void
    {
        $query->where('phone', $value);
    }

    public function getMoneyAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setMoneyAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    /**
     * 获取用户信息【过滤敏感字段】
     * @return UserModel
     */
    public function getUserInfo(): UserModel
    {
        return $this->hidden([
            'group_id', 'login_failure', 'join_ip', 'join_time', 'motto', 'password',
            'salt', 'status', 'create_time', 'update_time'
        ]);
    }

    public function getpid($uid){
        $list = $this->field('id,pid,hualuo')->where('pid',$uid)->select();
        if(count($list) >= 4){
            return $this->hualuo($list);
        }
        return $uid;
    }

    public function hualuo($plist){
        $setting = Db::name('recommend_setting')->where('name','max_people')->value('value');
        foreach ($plist as $k=>$p){
            $ids[] = $p['id'];
            $count = $this->where('pid',$p['id'])->count();
            $userlist = [];
            if($p['hualuo'] < $setting && $count < 4){
                $userlist[] = [
                    'id' => $p['id'],
                    'pid' => $p['pid'],
                    'hualuo' => $p['hualuo'],
                    'count' => $count
                ];
            }
            if($userlist){
                break;
            }
        }
        if(!$userlist){
            $pid = $this->hualuo($this->field('id,pid,hualuo')->where('pid','in',$ids)->order('pid')->select());
        }else{
            usort($userlist, function($a, $b) {
                if ($a['hualuo'] == $b['hualuo']) {
                    return $b['count'] - $a['count'];
                }
                return $b['count'] - $a['count'];
            });
            $pid = $userlist[0]['id'];
        }
        $this->where('id','=',$pid)->setInc('hualuo',1);
        return $pid;
    }


}
